package com.example.arithmeticleetcode.learnArithmetic.twonodetree;

import com.example.arithmeticleetcode.learnArithmetic.twonodetree.util.BinaryTreeInfo;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @program: arithmetic-leetcode
 * @description:
 * @author: FangZhen
 * @create: 2020-08-25 16:52
 **/
public class BinarySearchTree<E> implements BinaryTreeInfo {

    private int size;
    private Node<E> root;
    private Comparator<E> comparator;

    public BinarySearchTree() {
        this(null);
    }

    public BinarySearchTree(Comparator<E> comparator) {
        this.comparator = comparator;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void clear() {
        root = null;
        size = 0;
    }

    public void add(E element) {
        elementNotNullCheck(element);
        //添加第一个节点
        if (root == null) {
            root = new Node<>(element, null);
            size++;
            return;
        }
        //添加的不是第一个节点
        //找到父节点
        Node<E> parent = root;
        Node<E> node = root;
        int cmp = 0;
        while (node != null) {
            cmp = compare(element, node.element);
            parent = node;
            if (cmp > 0) {
                node = node.right;
            } else if (cmp < 0) {
                node = node.left;
            } else {
                //相等
                node.element = element;
                return;
            }
        }
        //查到父节点的位置
        Node<E> newNode = new Node<>(element, parent);
        if (cmp > 0) {
            parent.right = newNode;
        } else {
            parent.left = newNode;
        }
        size++;


    }

    public void remove(E element) {
        remove(node(element));
    }

    private void remove(Node<E> node) {
        if (node == null) return;
        size --;
        //度为2的节点
        if (node.hasTwoChildren()) {
            //找到后继节点
            Node<E> s = successor(node);
            //用后继节点的值覆盖度为2的值
            node.element = s.element;
            //删除后继节点
            node = s;
        }
        //删除node节点 node的度必为1或者0
        Node<E> replacement = node.left != null ? node.left : node.right;
        //node是度为1的节点
        if (replacement != null) {
            //更改parent
            replacement.parent = node.parent;
            //更改parent的left,right
            if (node.parent == null) {
                root = replacement;
            } else if (node == node.parent.left) {
                node.parent.left = replacement;
            } else {
                node.parent.right = replacement;
            }
        } else if (node.parent == null) {//node是叶子节点并且是根节点
            root = null;
        } else { //是叶子节点，但不是根节点
            if (node == node.parent.left) {
                node.parent.left = null;
            } else {
                node.parent.right = null;
            }
        }


    }

    private Node<E> node(E element) {
        Node<E> node = root;
        while (node != null) {
            int cmp = compare(element, node.element);
            if (cmp == 0) return node;
            if (cmp > 0) {
                node = node.right;
            } else {
                node = node.left;
            }
        }
        return null;
    }

    public boolean contains(E element) {
        return node(element) != null;
    }

    /**
     * 前序遍历 先遍历根节点，再遍历左子树，再遍历右子树  递归调用  根节点在前是前序遍历  根节点在中间是中序遍历  根节点在后面是后续遍历
     */
//    public void preOrderTraversal() {
//        preOrderTraversal(root);
//    }
//
//    private void preOrderTraversal(Node<E> node) {
//        if (node == null) return;
//        System.out.println(node.element);
//        preOrderTraversal(node.left);
//        preOrderTraversal(node.right);
//    }

    /**
     * 中序遍历 先遍历左子树，再遍历根节点，再遍历右子树  递归调用  中序遍历是升序或者降序的
     */
//    public void inOrderTraversal() {
//        inOrderTraversal(root);
//    }
//
//    private void inOrderTraversal(Node<E> node) {
//        if (node == null) return;
//        inOrderTraversal(node.left);
//        System.out.println(node.element);
//        inOrderTraversal(node.right);
//    }


    /**
     * @param e1
     * @param e2
     * @return 0 e1==e2 >0 e1>e2 <0 e1<e2
     */
    public int compare(E e1, E e2) {
        if (comparator != null) {
            return comparator.compare(e1, e2);
        }
        return ((Comparable<E>) e1).compareTo(e2);
    }

    /**
     * 后序遍历 先遍历左子树，再遍历右子树，再遍历根节点  递归调用  根节点在前是前序遍历  根节点在中间是中序遍历  根节点在后面是后续遍历
     */
//    public void postOrderTraversal() {
//        postOrderTraversal(root);
//    }
//
//    private void postOrderTraversal(Node<E> node) {
//        if (node == null) return;
//
//        postOrderTraversal(node.left);
//        postOrderTraversal(node.right);
//
//        System.out.println(node.element);
//    }

    /**
     * 层序遍历 从上到下 从左到右依次执行每一个节点 使用队列
     */
//    public void levelOrderTraversal() {
//        if (root == null) return;
//
//        Queue<Node<E>> queue = new LinkedList<>();
//
//        queue.offer(root);
//
//        while (!queue.isEmpty()) {
//            Node<E> poll = queue.poll();
//            System.out.println(poll.element);
//            if (poll.left != null) {
//                queue.offer(poll.left);
//            }
//            if (poll.right != null) {
//                queue.offer(poll.right);
//            }
//        }
//    }


    private void elementNotNullCheck(E element) {
        if (element == null) {
            throw new IllegalArgumentException("element must not be null");
        }
    }

    public void preOrder(Visitor<E> visitor) {
        if (visitor == null) return;
        preOrder(root, visitor);
    }

    private void preOrder(Node<E> node, Visitor<E> visitor) {
        if (node == null || visitor.stop) return;
        visitor.stop = visitor.visit(node.element);
        preOrder(node.left, visitor);
        preOrder(node.right, visitor);
    }

    public boolean isComplete() {
        if (root == null) return false;
        Queue<Node<E>> queue = new LinkedList<>();
        queue.offer(root);
        boolean leaf = false;
        while (!queue.isEmpty()) {
            Node<E> poll = queue.poll();
            if (leaf && !poll.isLeaf()) {
                return false;
            }
            if (poll.hasTwoChildren()) {
                queue.offer(poll.left);
                queue.offer(poll.right);
            } else if(poll.left == null && poll.right != null) {
                return false;
            } else {
                leaf = true;
            }
        }
        return true;
    }

    public int height() {
        return height1(root);
    }

    /**
     * 递归
     *
     * @param node
     * @return
     */
    private int height(Node<E> node) {
        if (node == null) return 0;
        return 1 + Math.max(height(node.left), height(node.right));
    }

    /**
     * 迭代
     *
     * @param node
     * @return
     */
    private int height1(Node<E> node) {
        if (node == null) return 0;

        Queue<Node<E>> queue = new LinkedList<>();

        int height = 0;
        //存储每一层的元素数量
        int levelSize = 1;
        queue.offer(root);

        while (!queue.isEmpty()) {
            Node<E> poll = queue.poll();
            levelSize --;
            if (poll.left != null) {
                queue.offer(poll.left);
            }
            if (poll.right != null) {
                queue.offer(poll.right);
            }
            if (levelSize == 0) {
                levelSize = queue.size();
                height ++;
            }
        }

        return height;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        toString(root, stringBuilder, "");
        return stringBuilder.toString();
    }

    private void toString(Node<E> node, StringBuilder sb, String prefix) {
        if (node == null) return;

        sb.append(prefix).append(node.element).append(System.lineSeparator());
        toString(node.left, sb, prefix + "L---");
        toString(node.right, sb, prefix + "R---");
    }

    public void inOrder(Visitor<E> visitor) {
        if (visitor == null) return;
        inOrder(root, visitor);
    }

    private void inOrder(Node<E> node, Visitor<E> visitor) {
        if (node == null || visitor.stop) return;

        inOrder(node.left, visitor);
        if (visitor.stop) {
            return;
        }
        visitor.stop = visitor.visit(node.element);
        inOrder(node.right, visitor);
    }

    public void postOrder(Visitor<E> visitor) {
        if (visitor == null) return;
        postOrder(root, visitor);
    }

    private void postOrder(Node<E> node, Visitor<E> visitor) {
        if (node == null || visitor.stop) return;

        postOrder(node.left, visitor);
        postOrder(node.right, visitor);
        if (visitor.stop) {
            return;
        }
        visitor.stop = visitor.visit(node.element);
    }

    public void levelOrder(Visitor<E> visitor) {
        if (root == null || visitor == null) return;

        Queue<Node<E>> queue = new LinkedList<>();

        queue.offer(root);

        while (!queue.isEmpty()) {
            Node<E> poll = queue.poll();
            if (visitor.visit(poll.element)) {
                return;
            }
            if (poll.left != null) {
                queue.offer(poll.left);
            }
            if (poll.right != null) {
                queue.offer(poll.right);
            }
        }
    }

    public Node<E> preDesessor(Node<E> node) {
        if (node == null) return null;
        //前驱节点在左子树上 <left, right>
        Node<E> p = node.left;
        if (p != null) {
            while (p.right != null) {
                p = p.right;
            }
            return p;
        }
        //从祖父节点
        while (node.parent != null && node == node.parent.left) {
            node = node.parent;
        }

        return node.parent;

    }

    public Node<E> successor(Node<E> node) {
        if (node == null) return null;
        //前驱节点在左子树上 <left, right>
        Node<E> p = node.right;
        if (p != null) {
            while (p.left != null) {
                p = p.left;
            }
            return p;
        }
        //从祖父节点
        while (node.parent != null && node == node.parent.right) {
            node = node.parent;
        }
        return node.parent;
    }

    public static abstract class Visitor<E> {

        boolean stop;

        /**
         * 返回true停止遍历
         *
         * @param element
         * @return
         */
        public abstract boolean visit(E element);
    }

    private static class Node<E> {
        E element;
        Node<E> left;
        Node<E> right;
        Node<E> parent;

        public Node(E element, Node<E> parent) {
            this.element = element;
            this.parent = parent;
        }

        public boolean isLeaf() {
            return left == null && right == null;
        }

        public boolean hasTwoChildren(){
            return left != null && right != null;
        }
    }


    @Override
    public Object root() {
        return root;
    }

    @Override
    public Object left(Object node) {
        return ((Node<E>) node).left;
    }

    @Override
    public Object right(Object node) {
        return ((Node<E>) node).right;
    }

    @Override
    public Object string(Object node) {
        Node<E> myNode = (Node<E>) node;
        String parentString = "null";
        if (myNode.parent != null) {
            parentString = myNode.parent.element.toString();
        }
        return myNode.element; //+ "_p(" + parentString + ")";
    }
}
